import React, { useState, useEffect, useRef, useCallback } from 'react';
import { AgGridReact } from 'ag-grid-react';
import { Modal, message, Form, Input } from 'antd';
import 'ag-grid-community/styles/ag-grid.css';
import 'ag-grid-community/styles/ag-theme-alpine.css';
import api from '../../utils/api';

const UserGrid: React.FC = () => {
    const gridRef = useRef<any>(null); // 引用 AG Grid 组件的引用，用于访问其 API
    const [loading, setLoading] = useState(false); // 加载状态，指示数据是否正在加载
    const [error, setError] = useState<string | null>(null); // 错误状态，存储加载或操作过程中出现的错误信息
    const [deleteLoading, setDeleteLoading] = useState(false); // 删除状态，指示是否正在进行删除操作
    const [rowData, setRowData] = useState<any[]>([]); // 行数据，存储从服务器获取的用户数据
    const [totalRecords, setTotalRecords] = useState(0); // 总记录数，存储用户数据的总条数，用于分页显示
    const [selectedRows, setSelectedRows] = useState<any[]>([]); // 选中的行数据，存储用户在表格中选择的用户信息
    const [columnDefs] = useState([
        { field: 'id', headerName: 'ID', width: 80 },
        { field: 'username', headerName: '用户名', sortable: true, filter: true },
        {
            field: 'created_at',
            headerName: '创建时间',
            sortable: true,
            filter: true,
            valueFormatter: (params: any) => {
                if (params.value) {
                    return new Date(params.value).toLocaleString();
                }
                return '';
            }
        },
        {
            headerName: '操作',
            width: 200,
            sortable: false,
            filter: false,
            resizable: false,
            flex: 0,
            cellRenderer: (params: any) => {
                return (
                    <div className="flex justify-center items-center gap-3 w-full h-full">
                        <button
                            className="bg-blue-500 hover:bg-blue-600 text-white text-xs font-medium py-1.5 px-3 rounded-lg shadow-sm min-w-[50px]"
                            onClick={() => handleEdit(params.data)}
                        >
                            编辑
                        </button>
                        <button
                            className="bg-red-500 hover:bg-red-600 text-white text-xs font-medium py-1.5 px-3 rounded-lg shadow-sm min-w-[50px]"
                            onClick={() => handleDelete(params.data.id, params.data.username)}
                        >
                            删除
                        </button>
                    </div>
                );
            }
        }
    ]);
    // 添加编辑相关的状态
    const [isEditModalVisible, setIsEditModalVisible] = useState(false);
    const [editingUser, setEditingUser] = useState<any>(null);
    const [form] = Form.useForm();
    // 加载数据
    const loadData = useCallback(async () => {
        setLoading(true);
        setError(null);
        try {
            const response = await api.get('/users');
            setRowData(response.data);
            setTotalRecords(response.data.length);
            setLoading(false);
        } catch (error) {
            console.error('加载数据失败:', error);
            setError('获取用户数据失败，请稍后重试。');
            setLoading(false);
        }
    }, []);
    // 组件挂载时加载数据
    useEffect(() => {
        loadData();
    }, [loadData]);
    const handleEdit = (user: any) => {
        setEditingUser(user);
        form.setFieldsValue({
            username: user.username,
            email: user.email,
            // 设置其他需要编辑的字段
        });
        setIsEditModalVisible(true);
    };
    const pageSizeOptions = [10, 20, 50, 100];
    const handleDelete = (id: number, username: string) => {
        // 使用 Ant Design 的 Modal 组件进行确认
        Modal.confirm({
            title: '确认删除',
            content: `确定要删除用户${username ? ' "' + username + '"' : ''}吗？`,
            okText: '确认',
            cancelText: '取消',
            onOk: async () => {
                setLoading(true);
                setError(null);
                try {
                    const response = await api.delete(`/users/${id}`);
                    // 使用 Ant Design 的 message 组件显示成功提示
                    message.success(response.data?.message || '用户删除成功！');
                    loadData(); // 重新加载数据
                } catch (error) {
                    console.error('删除用户失败:', error);
                    setError('删除用户失败，请稍后重试。');
                } finally {
                    setLoading(false);
                }
            },
            onCancel() {
                console.log('取消删除');
            },
        });
    };
    const refreshData = () => {
        loadData();
    };
    const onSelectionChanged = (event: any) => {
        const selectedNodes = event.api.getSelectedNodes();
        const selectedData = selectedNodes.map((node: any) => node.data);
        setSelectedRows(selectedData);
    };
    const handleBatchDelete = async () => {
        if (selectedRows.length === 0) {
            setError('请先选择要删除的用户');
            return;
        }
        if (window.confirm(`确定要删除选中的 ${selectedRows.length} 个用户吗？`)) {
            setDeleteLoading(true);
            setError(null);
            try {
                const ids = selectedRows.map(row => row.id);
                await api.post('/users/batch-delete', { ids });
                message.success(`成功删除 ${selectedRows.length} 个用户`);
                loadData();
            } catch (error) {
                console.error('批量删除失败:', error);
                setError('批量删除失败，请稍后重试');
            } finally {
                setDeleteLoading(false);
            }
        }
    };
    // 添加处理编辑提交的函数
    const handleEditSubmit = async () => {
        try {
            const values = await form.validateFields();
            if (editingUser?.id) {
                await api.put(`/auth/users/${editingUser.id}`, values);
                message.success('用户信息更新成功');
                setIsEditModalVisible(false);
                loadData(); // 重新加载数据
            }
        } catch (error) {
            console.error('更新用户失败:', error);
            message.error('更新用户信息失败');
        }
    };
    // 添加关闭模态框的函数
    const handleEditCancel = () => {
        setIsEditModalVisible(false);
        form.resetFields();
    };
    return (
        <div className="w-full bg-white rounded-lg shadow-md overflow-hidden">
            <div className="px-6 py-4 bg-blue-50 border-b border-gray-200">
                <div className="flex justify-between items-center">
                    <h2 className="text-xl font-bold text-gray-800">用户管理</h2>
                    <div className="flex gap-2">
                        {selectedRows.length > 0 && (
                            <button
                                className="bg-red-500 hover:bg-red-600 text-white px-4 py-2 rounded flex items-center"
                                onClick={handleBatchDelete}
                                disabled={deleteLoading || loading}
                            >
                                <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                </svg>
                                删除选中({selectedRows.length})
                            </button>
                        )}
                        <button
                            className="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded flex items-center"
                            onClick={refreshData}
                            disabled={loading || deleteLoading}
                        >
                            <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                            </svg>
                            刷新数据
                        </button>
                    </div>
                </div>
                {loading && (
                    <div className="mt-2 text-blue-600">正在加载数据...</div>
                )}
                {deleteLoading && (
                    <div className="mt-2 text-blue-600">正在删除用户...</div>
                )}
                {error && (
                    <div className="mt-2 text-red-500 bg-red-50 p-2 rounded border border-red-200">{error}</div>
                )}
            </div>
            {/* 添加编辑用户的模态框 */}
            <Modal
                title="编辑用户信息"
                open={isEditModalVisible}
                onOk={handleEditSubmit}
                onCancel={handleEditCancel}
                okText="保存"
                cancelText="取消"
            >
                <Form
                    form={form}
                    layout="vertical"
                    initialValues={{}}
                >
                    <Form.Item
                        name="username"
                        label="用户名"
                        rules={[{ required: true, message: '请输入用户名' }]}
                    >
                        <Input placeholder="请输入用户名" />
                    </Form.Item>

                    <Form.Item
                        name="email"
                        label="邮箱"
                        rules={[
                            { required: true, message: '请输入邮箱' },
                            { type: 'email', message: '请输入有效的邮箱地址' }
                        ]}
                    >
                        <Input placeholder="请输入邮箱" />
                    </Form.Item>

                    {/* 可以根据需要添加更多表单项 */}
                </Form>
            </Modal>
            <div className="p-6">
                <div
                    className="ag-theme-alpine rounded border border-gray-200"
                    style={{ height: 500, width: '100%' }}
                >
                    <AgGridReact
                        ref={gridRef}
                        rowData={rowData}
                        columnDefs={columnDefs}
                        defaultColDef={{
                            flex: 1,
                            minWidth: 100,
                            resizable: true,
                            sortable: true,
                            filter: true
                        }}
                        rowSelection="multiple"
                        onSelectionChanged={onSelectionChanged}
                        pagination={true}
                        paginationPageSizeSelector={pageSizeOptions}
                    />
                </div>
                <div className="mt-4 text-sm text-gray-500">
                    共 {totalRecords} 条记录
                </div>
            </div>
        </div>
    );
};
export default UserGrid;